<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="任务名称" prop="name">
        {{'TASK'+seriesIoForm.channel}}
      </el-form-item>
        <el-form-item label="触发标识" prop="triggerFlag">
          <template>
            <el-radio v-model="form.triggerFlag" label="T">定时触发</el-radio>
            <el-radio v-model="form.triggerFlag" label="DI">开关量触发</el-radio>
            <el-radio v-model="form.triggerFlag" label="ST">上电触发</el-radio>
            <el-radio v-model="form.triggerFlag" label="GW">阈值触发</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="执行方式" prop="taskModel" v-if="form.triggerFlag === 'T'">
          <template>
            <el-radio v-model="form.taskModel" label="LOOP">循环执行</el-radio>
            <el-radio v-model="form.taskModel" label="SINGLE">执行一次</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="执行周期" prop="taskModel" v-if="form.triggerFlag === 'T' && form.taskModel === 'LOOP'">
          <template>
            <el-checkbox-group v-model="form.weeks">
              <el-checkbox label="0">星期日</el-checkbox>
              <el-checkbox label="1">星期一</el-checkbox>
              <el-checkbox label="2">星期二</el-checkbox>
              <el-checkbox label="3">星期三</el-checkbox>
              <el-checkbox label="4">星期四</el-checkbox>
              <el-checkbox label="5">星期五</el-checkbox>
              <el-checkbox label="6">星期六</el-checkbox>
            </el-checkbox-group>
          </template>
        </el-form-item>
        <el-form-item label="执行时间" prop="taskModel" v-if="form.triggerFlag === 'T' && form.taskModel === 'LOOP'">
            <el-time-picker v-model="form.time" value-format="HH:mm:ss" placeholder="请选择执行时间"> </el-time-picker>
        </el-form-item>
        <el-form-item label="执行时间" prop="taskModel" v-if="form.triggerFlag === 'T' && form.taskModel === 'SINGLE'">
          <el-date-picker v-model="form.dateTime" type="datetime" value-format="yyyy/MM/dd HH:mm:ss" placeholder="选择日期时间"> </el-date-picker>
        </el-form-item>  
        <el-form-item label="开关执行条件" prop="displayModel" v-if="form.triggerFlag==='DI'">
          <div class="option-box">
            <el-table
              size="mini"
              :data="switchList"
              border
              style="width: 100%">
              <el-table-column label="序号" width="70" type="index" align="center"></el-table-column>
              <el-table-column align="center"  label="工作模式">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.taskModel" placeholder="请选择工作模式">
                    <el-option label="启动任务" value="3" />
                    <el-option label="重新启动" value="4" />
                    <el-option label="等待停止" value="5" />
                    <el-option label="停止任务" value="6" />
                    <el-option label="退出任务" value="7" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center"  label="开关通道">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.channel" placeholder="请选择开关通道">
                    <el-option
                      v-for="item in channels"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center"  label="触发条件">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.value" placeholder="请选择触发条件">
                    <el-option label="低电平" value="0">低电平</el-option>
                    <el-option label="高电平" value="1">高电平</el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="70" >
                <template slot-scope="scope">
                  <i class="el-icon-delete" style="cursor: pointer;" @click.stop="delSwitch(scope.$index,scope.row)" ></i>
                </template>
              </el-table-column>
            </el-table>
            <el-button class="add-btn" type="primary" icon="el-icon-plus" @click="addSwitch" >添加选项</el-button>
          </div>
        </el-form-item>      
        <el-form-item label="阈值执行条件" prop="displayModel" v-if="form.triggerFlag==='GW'">
          <div class="option-box">
            <el-table
              size="mini"
              :data="optionList"
              border
              style="width: 100%">
              <el-table-column label="序号" width="70" type="index" align="center"></el-table-column>
              <el-table-column align="center"  label="工作模式">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.taskModel" placeholder="请选择工作模式">
                    <el-option label="启动任务" value="3" />
                    <el-option label="重新启动" value="4" />
                    <el-option label="等待停止" value="5" />
                    <el-option label="停止任务" value="6" />
                    <el-option label="退出任务" value="7" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center"  label="数据源">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.sourceFlag" placeholder="请选择数据源" value-key="flag">
                    <el-option
                      v-for="item in sensorList"
                      :key="item.id"
                      :label="item.name"
                      :value="item"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center"  label="触发条件">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.condition" placeholder="请选择显示方式">
                    <el-option label="等于" value="0" />
                    <el-option label="小于" value="1" />
                    <el-option label="大于" value="2" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="阈值设置">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.value" placeholder="请输入阈值" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="持续时间（秒）">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.times" placeholder="请输入持续时间" :min="1" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="70" >
                <template slot-scope="scope">
                  <i class="el-icon-delete" style="cursor: pointer;" @click.stop="delOption(scope.$index,scope.row)" ></i>
                </template>
              </el-table-column>
            </el-table>
            <el-button class="add-btn" type="primary" icon="el-icon-plus" @click="addOption" >添加选项</el-button>
          </div>
        </el-form-item>
        <el-form-item label="输出动作" prop="displayModel">
          <div class="option-box">
            <el-table
              size="mini"
              :data="actionList"
              border
              style="width: 100%">
              <el-table-column label="序号" width="70" type="index" align="center"></el-table-column>
              <el-table-column align="center"  label="关联标识">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.model" placeholder="请选择关联标识">
                    <el-option label="任务开始" value="0" />
                    <el-option label="任务结束" value="1" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center"  label="开关">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.source" placeholder="请选择开关" value-key="flag" @change="scope.row.outAction=''">
                    <el-option
                      v-for="item in controllerList"
                      :key="item.id"
                      :label="item.name"
                      :value="item"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center"  label="输出动作">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.outAction" placeholder="请选择输出动作" @change="sourceFlagChange(scope.row)">
                    <el-option
                      v-for="item in scope.row.source.commandList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="开关定时(秒)">
                <template slot-scope="scope" v-if="scope.row.action == 2 || scope.row.action == 3">
                  <el-input v-model="scope.row.timesSwitch" placeholder="请输入点动定时" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="持续时间(秒)">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.times" placeholder="请输入持续时间" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="70" >
                <template slot-scope="scope">
                  <i class="el-icon-delete" style="cursor: pointer;" @click.stop="delAction(scope.$index,scope.row)" ></i>
                </template>
              </el-table-column>
            </el-table>
            <el-button class="add-btn" type="primary" icon="el-icon-plus" @click="addAction" >添加选项</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
  </div>
</template>

<script>
import code from '../cmdData/code'
export default {
  props:{
    deviceId:'',
    seriesIoForm:null,
    sensorList:null,
    controllerList:null
  },
  dicts: ['cmd_execute_status'],
  components:{'v-code':code},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备命令执行日志表格数据
      cmdDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      channels:[],
      // 表单校验
      rules: {
      },
      jsonPopup:false,
      optionList:[],
      actionList:[],
      switchList:[]
    };
  },
  created() {
    for(var i = 1 ; i <= 64 ; i++){
      this.channels.push({value:i+"",name:"开关通道"+i})
    }
    this.reset()
    this.initForm();
  },
  methods: {
    initForm(){
      if(!this.seriesIoForm.commandList) return false;
      let result = this.seriesIoForm.commandList[0].value.substring(2);
    //   console.log('--------result')
    //   console.log(result)
      
      let taskNameIndex = result.indexOf(',')
      let taskName = result.substring(0,taskNameIndex)
      this.form.name = taskName;
      result = result.substring(taskNameIndex+1);

      var idx = result.indexOf('],') ;
      //获取触发模式
      while(idx>0){
        let taskTriggerIndex = idx + 1;
        let triggerIndex = result.indexOf(':')
        let trigger = result.substring(1,triggerIndex);
        let valuesStr = result.substring(0,taskTriggerIndex).replaceAll(trigger+':','');
        valuesStr = valuesStr.replaceAll(',','\',\'')
        valuesStr = valuesStr.replaceAll('[','[\'')
        valuesStr = valuesStr.replaceAll(']','\']')
        console.log(valuesStr)
        let values = eval('('+valuesStr+')');
        result = result.substring(taskTriggerIndex+1);
        let opt = {}
        if(trigger === 'GW'){
          this.form.triggerFlag = 'GW'
          opt.taskModel = values[0]
          opt.sourceFlag = this.getSource(this.sensorList,values[1]) 
          opt.condition = values[2]
          opt.value = values[3]
          opt.times = values[4]
          this.optionList.push(opt)
        }
        else if(trigger === 'T'){
          this.form.triggerFlag = 'T'
          this.form.taskModel = values[1] == 7 ? 'SINGLE' : 'LOOP'
          this.form.weeks = values[1] == 7 ? [] : values[1].split('|')
          this.form.time = values[1] == 7 ? '' : values[2]
          this.form.dateTime = values[1] == 7 ? values[2] : ''
        }
        else if(trigger === 'DI'){
          this.form.triggerFlag = 'DI'
          opt.taskModel = values[0]
          opt.channel = values[1]
          opt.value = values[2]
          this.switchList.push(opt)
        }
        else if(trigger === 'DO'){
          opt.model = values[0]+''
          opt.action = values[2]+''
          opt.channel = values[1]
          opt.source = this.getControl(this.controllerList,opt)
          opt.times = ''
          this.sourceSelect(opt)
          opt.timesSwitch = (opt.action == 2 || opt.action == 3) ? values[3] : ''
          this.actionList.push(opt)
        }
        else if(trigger === 'DY' && values[1]!='undefined'){
          let obj = this.actionList[this.actionList.length-1]
          obj.times = values[1]+''
        }
        idx = result.indexOf('],') 
      }
    },
    // 取消按钮
    cancel() {
      this.jsonPopup = false;
      this.$emit("cancel",null)
    },
    // 表单重置
    reset() {
      this.form = {
        model:'',
        channel:'',
        value:'',
        triggerFlag:'ST',
        taskModel:'',
        dateTime:'',
        time:'',
        weeks:[],
        gwList:[],
        osList:[]
      };
      this.resetForm("form");
    },
    addOption(){
      this.optionList.push({
        taskModel:'',
        sourceFlag:null,
        condition:'',
        value:'',
        times:'1'
      })
      this.$nextTick()
    },
    delOption(index,row){
      this.optionList.splice(index,1)
    },
    addAction(){
      this.actionList.push({
        model:'0',
        source:{flag:'',channel:'',commandList:[]},
        outAction:'',
        action:'',
        times:'100000'
      })
      this.$nextTick()
    },
    delAction(index,row){
      this.actionList.splice(index,1)
    },
    addSwitch(){
      this.switchList.push({
        taskModel:'3',
        channel:null,
        value:''
      })
    },
    delSwitch(index,row){
      this.switchList.splice(index,1)
    },
    sourceFlagChange(row){
      row.action = row.outAction.split(',')[0] ;
    },
    sourceSelect(opt){
      let commandList = opt.source.commandList;
      let command = commandList.filter( o => o.value.startsWith(opt.action))[0];
      opt.outAction = command.value ;
    },
    getControl(sourceArray , opt){
      let contolList = sourceArray.filter( o => o.channel == opt.channel);
      for(var i = 0 ; i < contolList.length ; i++){
        if(contolList[i] && contolList[i].commandList){
          let commandList = contolList[i].commandList;
          let command = commandList.filter( o => o.value.startsWith(opt.action))[0];
          if(command!=null) return contolList[i];
        }
      }
      return contolList[0];
    },
    getSource(sourceArray , channel){
      return sourceArray.filter( o => o.channel == channel)[0];
    },
    /** 提交按钮 */
    submitForm() {
      //2,TEST_TASK1,[GW:3,2,2,310,1],[GW:6,2,1,330,1],[DO:0,1,1],[DY:0,100000],[DO:1,1,0],[N:1,0]
      let taskName = 'TASK'+this.seriesIoForm.channel;
      let result = '2,'+taskName+',';
      let form = this.form;
      if(form.triggerFlag === 'GW'){
        for(var i in this.optionList){
          let opt = this.optionList[i];
          //'['+form.triggerFlag+':'+this.optionList[i].taskModel+','+this.getTaskIndex()
          result += `[${form.triggerFlag}:${opt.taskModel},${opt.sourceFlag.channel},${opt.condition},${opt.value},${opt.times}],`
        }
      }
      //开关量触发
      else if(form.triggerFlag === 'DI'){
        for(var i in this.switchList){
          let opt = this.switchList[i];
          result += `[${form.triggerFlag}:${opt.taskModel},${opt.channel},${opt.value}],`
        }
      }
      else if(form.triggerFlag === 'T'){
        let week = form.taskModel==='LOOP' ? form.weeks.join('|') :'7' 
        let times = form.taskModel==='LOOP'? form.time : form.dateTime;
        result += `[${form.triggerFlag}:3,${week},${times}],`
      }
      else if(form.triggerFlag === 'ST'){
        result += `[${form.triggerFlag}:3],`
      }
      //动作接
      for(var i in this.actionList){
          let opt = this.actionList[i];
          //'['+form.triggerFlag+':'+this.optionList[i].taskModel+','+this.getTaskIndex()
          result += `[DO:${opt.model},${opt.source.channel},${opt.action}${(opt.action==2 || opt.action==3)?','+opt.timesSwitch:''}],`
          if(opt.times && opt.times !== '100000'){
            result += `[DY:${opt.model},${opt.times}],`
          }
        }
      result += '[N:1,0]'
      let options = [];
      options.push({name:'添加任务',value:result,sort:1})
      options.push({name:'启动任务',value:'3,'+taskName,sort:2})
      options.push({name:'停止任务',value:'6,'+taskName,sort:2})
      options.push({name:'删除任务',value:'1,'+taskName,sort:2})
      this.$emit("success",options)
    },
    getTaskIndex(flag){
      return flag.substring(flag.length-1)
    }
  },
  watch:{
    sensorId(v){
      if(v){
        this.queryParams.deviceId = this.deviceId;
        this.queryParams.sensorId = this.sensorId||'';
        this.getList();
      }
    }
  }
};
</script>
